package cn.gson.CRM.service.permission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.gson.CRM.model.dao.permission.ResourceDao;
import cn.gson.CRM.model.entity.Resource;
import cn.gson.CRM.model.mapper.ResourceMapper;

@Service
public class ResourceService {

	@Autowired
	ResourceMapper resourceMapper;

	@Autowired
	ResourceDao resourceDao;

	public List<Resource> getTreeData() {
		// 获取到根节点
		List<Resource> roots = resourceMapper.selectRoot();
		// 递归出所有子节点
		this.recursion(roots);

		return roots;
	}

	private void recursion(List<Resource> node) {
		for (Resource resource : node) {
			List<Resource> children = resourceMapper.selectChildren(resource.getId());
			this.recursion(children);
			resource.setChildren(children);
		}
	}

	public List<Map<String, Object>> getGrantTreeData(List<Resource> resources) {
		List<Resource> roots = resourceDao.findByParentIsNullAndEnable(true);

		return this.recursion2(roots, resources);
	}

	private List<Map<String, Object>> recursion2(List<Resource> node, List<Resource> checked) {
		List<Map<String, Object>> treeData = new ArrayList<>();
		for (Resource resource : node) {
			Map<String, Object> tnode = new HashMap<>();
			tnode.put("id", resource.getId());
			tnode.put("text", resource.getText());
			
			List<Resource> children = resourceDao.findByParentAndEnable(resource, true);
			//只在根节点上,标识选中状态
			if(children.size() == 0) {
				tnode.put("checked", checked.contains(resource));
			}
			tnode.put("children", this.recursion2(children, checked));
			treeData.add(tnode);
		}
		return treeData;
	}
}
